<template>
    <el-dialog v-model="templateViewVisible" :width="width" class="custom-dialog template-dialog" :show-close='false'
        :close-on-click-modal="modalClose" modal-class="dialog-center" :before-close="handleClose">
        <div class="custom-dialog-header template-view-header">
            <div class="template-title">
                <svg class="file-icon">
                    <use v-bind:xlink:href="getIcon(templateInfo.type, templateInfo.nameSuffix)"></use>
                </svg>
                <div class="title-or-user">
                    <div class="title">{{ templateInfo.name }}</div>
                    <div class="author">{{ $t('message.text.author') }}：{{ templateInfo.createBy }}</div>
                </div>
            </div>
            <svg class="close-icon" @click="handleClose">
                <use xlink:href="#keowledge-danchuangguanbi1"></use>
            </svg>
        </div>
        <el-scrollbar>
            <div class="template-view-body" v-loading="templateLoading">
                <aomao-editor v-if="templateInfo.type == 'document_html'" v-show="!showTemplateInvoke" :isRead="true"
                    :id="templateInfo.id" :formShare="true" :isWritingPreview="true" :showMenuBar="false"
                    :isTemplate="true" />
                <LuckySheet v-if="templateInfo.type == 'document_xlsx'" v-show="!showTemplateInvoke" :isEdit="false"
                    :id="templateInfo.id" :isWriting="true" :readonly="true" :formShare="true" :isTemplate="true">
                </LuckySheet>
                <MindElixir v-if="templateInfo.type == 'document_map'" v-show="!showTemplateInvoke"
                    :id="templateInfo.id" :readonly="true" :formShare="true" :isTemplate="true"></MindElixir>
                <Topology v-if="templateInfo.type == 'document_flow'" v-show="!showTemplateInvoke" :id="templateInfo.id"
                    :readonly="true" :formShare="true" :isTemplate="true"></Topology>
                <MonitorOffice v-if="isOnlyOffice" :option="option" v-show="!showTemplateInvoke" ref="monitorOffice"
                    :isTemplate="true"></MonitorOffice>
                <templateInvoke v-if="showTemplateInvoke" :id="templateInfo.id" :savePathObj="savePathObj"
                    @openSelectSavePath="openSelectSavePath"></templateInvoke>
            </div>
        </el-scrollbar>
        <template #footer v-if="showFooter">
            <div class="know-footer">
                <el-button v-if="templateType == 'text'"
                    @click="handleSave('save')">{{ $t('message.buttons.saveToLibrary') }}</el-button>
                <el-button v-if="templateType == 'text'" type="primary"
                    @click="handleSave('imUse')">{{ $t('message.buttons.immediateUse') }}</el-button>
                <el-button v-if="templateType == 'variable' && !showTemplateInvoke" type="primary"
                    @click="changeInvoke">{{ $t('message.buttons.viewCallInfo') }}</el-button>
                <el-button v-if="templateType == 'variable' && showTemplateInvoke"
                    @click="changeInvoke">{{ $t('message.buttons.back') }}</el-button>
            </div>
        </template>
    </el-dialog>
    <selectKnow ref="saveKnowRef" :title="$t('message.text.saveLocation')" :key='selectType == "savePath"'
        :isTemplate='selectType == "savePath"' @callBack="getCheckedFile"></selectKnow>
</template>

<script setup lang="ts">
import {
    ref,
    reactive,
    toRefs,
    watch,
    onMounted,
    computed,
    nextTick,
    getCurrentInstance
} from 'vue'
import { useRouter } from "vue-router"
import selectKnow from '@/views/selectKnow/index.vue'
import aomaoEditor from '@/components/aomaoEditor/index.vue'
import LuckySheet from '@/components/luckySheet/index.vue'
import MindElixir from '@/components/mindElixir/index.vue'
import Topology from "@/components/topology/index.vue";
import MonitorOffice from "@/components/monitor-office/monitorOffice.vue";
import templateInvoke from './templateInvoke.vue'
import { isOffice } from "@/utils/util"
import { getTemplateInfo, saveTempFilePath } from '@/api/template'
import { addLibrary } from '@/api/knowledge'
import useUserInfoStore from '@/store/userInfo'
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const userStore = useUserInfoStore()
const router = useRouter();
const saveKnowRef = ref()
const emit = defineEmits([""])
const { proxy } = getCurrentInstance()
const props = defineProps({
    width: {
        type: String,
        default: '900px'
    },
    remove: Function,
    callBack: Function,
    templateInfo: {
        type: Object,
        default() {
            return {}
        }
    },
    parentId: {
        type: String,
    },
    parentName: {
        type: String,
    },
    templateType: {
        type: String,
        default: 'text'
    },
    modalClose: {
        type: Boolean,
        default: false
    },
    isTemplate: {
        type: Boolean,
        default: false
    },
    showFooter: {
        type: Boolean,
        default: true
    }
})

const templateViewVisible = ref(false)
const showTemplateInvoke = ref(false)
const isOnlyOffice = ref(false)
const BASE_URL = (window.location.protocol + window.pluginConfig.officeCallBackUrl.substring(window.pluginConfig.officeCallBackUrl.indexOf('://') + 1)) || ''
const option = ref({
    url: "",
    isEdit: true,
    id: '',
    mode: 'edit',
    comment: false,
    fileType: "",
    title: "",
    editUrl: BASE_URL + `/mgr/document/no/auth/only/office`,// mgr/document
    addUrl: BASE_URL + `/mgr/document/dcLibrary/office/add`,
})
const monitorOffice = ref()
const templateLoading = ref(false)
const selectType = ref('other')
const sendQuery = ref({})
const savePathObj = ref({
    savePathId: '',
    savePathName: '',
})
onMounted(() => {
    init()
})
const selectFileType = ref('')
function init() {
    templateViewVisible.value = true
    templateLoading.value = true
    if (props.templateInfo.type == 'document_upload' || isOffice(props.templateInfo.type)) {
        getTemplateInfo(props.templateInfo.id, {
            templateType: props.templateType
        }).then(res => {
            if (res.data.code == 0) {
                if (['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'csv'].indexOf(props.templateInfo.nameSuffix) != -1 && isOffice(props.templateInfo.type)) {
                    isOnlyOffice.value = true
                    nextTick(() => {
                        savePathObj.value.savePathId = res.data.data.savePathId || ''
                        savePathObj.value.savePathName = res.data.data.savePathName || ''
                        oepnOnlyOffice(res.data.data)
                    })
                }
            }
            setTimeout(() => {
                templateLoading.value = false
            }, 500)
        })
        isOnlyOffice.value = true
    } else {
        setTimeout(() => {
            templateLoading.value = false
        }, 500)
    }
}
function oepnOnlyOffice(data) {
    option.value.id = data.key
    if (!option.value.id) {
        option.value.id = props.templateInfo.id + userStore.userInfo?.id
    }
    option.value.addUrl = data.key
    option.value.title = ' '
    option.value.fileType = props.templateInfo.nameSuffix
    option.value.isEdit = false
    option.value.comment = false
    option.value.mode = 'view'
    option.value.url = data.fileLink
    if (userStore.userInfo?.id) {
        option.value.editUrl = `${BASE_URL}/mgr/document/only/office?id=${props.templateInfo?.id}&userId=${userStore.userInfo?.id}&userName=${userStore.userInfo?.realName}&isTemple=false&tenantId=${userStore.userInfo?.tenantId}`
    } else {
        option.value.editUrl = `${BASE_URL}/mgr/document/only/office?id=${props.templateInfo?.id}&userId=&userName=&isTemple=false&tenantId=`
    }
    monitorOffice.value.init()
}
function handleClose() {
    isOnlyOffice.value = false
    if (props.remove) props.remove()
    templateViewVisible.value = false
}
function handleSave(val) {
    selectFileType.value = val
    selectType.value = 'other'
    if (!props.parentId) {
        saveKnowRef.value.init()
    } else {
        getCheckedFile({
            id: props.parentId,
        })
    }
}
function changeInvoke() {
    showTemplateInvoke.value = !showTemplateInvoke.value
}
function getCheckedFile(item) {
    if (selectType.value == 'other') {
        sendQuery.value = { fileType: props.templateInfo.type, id: item.id, name: $t('message.text.unnamedFile'), templateId: props.templateInfo.id, parentId: item.id }
        sendCreateFile()
    } else {
        savePathObj.value.savePathId = item.id
        savePathObj.value.savePathName = item.name
        saveTempFilePath({
            ...props.templateInfo,
            ...savePathObj.value
        }).then(res => {
            if (res.data.code == 0) {
                proxy.$notify({
                    title: $t('message.prompt'),
                    message: $t('message.message.changeSaveLoactionSuccess'),
                    type: 'success',
                    position: 'bottom-right'
                })
            }
        })
    }
}
function sendCreateFile() {
    addLibrary(sendQuery.value).then(res => {
        if (res.data.code == 0) {
            let title = ''
            if (selectFileType.value != 'save') {
                title = $t('message.message.useTemplateCreateSuccess')
            } else {
                title = $t('message.message.saveLibrarySuccess')
            }
            proxy.$notify({
                title: (title),
                type: 'success',
                position: 'bottom-right'
            });
            if (res.data.data && selectFileType.value != 'save') {
                const tempData = JSON.parse(JSON.stringify(res.data.data))
                if (["document_map", "document_xlsx", "document_flow", "document_html"].indexOf(tempData.type) > -1) {
                    proxy.$openUrl(`/#/editor?knowId=${tempData.knowledgeId}&docId=${tempData.id}&formId=1`, '_blank')
                }
                if (isOffice(tempData.type) && ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'csv'].indexOf(tempData.nameSuffix) != -1) {
                    setTimeout(() => {
                        proxy.$openUrl(`/#/editorOffice?knowId=${tempData.knowledgeId}&docId=${tempData.id}&formId=1`, '_blank')
                    }, 1000 * 0.2)
                }
            }
            handleClose()
        }
    })
}
function openSelectSavePath() {
    selectType.value = 'savePath'
    saveKnowRef.value.init()
}
</script>
<style lang="scss" scoped>
.template-view-header {
    .template-title {
        display: flex;
        align-items: center;

        .file-icon {
            width: 24px;
            height: 24px;
            margin-right: 9px;
        }

        .title-or-user {
            .title {
                color: #363B4C;
                font-size: 14px;
            }

            .author {
                font-size: 10px;
                color: #6F7588;
            }
        }
    }
}

.template-view-body {
    max-height: calc(100vh - 252px);
    min-height: 552px;
}

.know-footer {
    padding: 16px;
    box-sizing: border-box;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: end;
    border-top: 1px solid #EEEFF0;

    button {
        padding: 0px 15px !important;
    }
}
</style>
<style lang="scss">
.template-dialog {
    width: 900px !important;
}
</style>